//
//  UIImage-Extensions.m
//  The9AdPlatform
//
//  Created by zhang xiaodong on 11-5-31.
//  Copyright 2011 the9. All rights reserved.
//

#import "UIImage-Extensions.h"


CGFloat CSDegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat CSRadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};

@implementation UIImage (CS_Extensions)
-(UIImage *)getImageByScrollingAndScalingAndCroppingForSize:(CGSize )targetSize{
    UIImage* sourceImage = self;
    CGContextRef contextRef=NULL;
    CGImageRef resultImageRef=NULL;
    UIImage* resultImage=nil;
    
    CGImageRef imageRef = [sourceImage CGImage];
    
    UIImageOrientation orientation = self.imageOrientation;
    
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
    
    /*
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
    if (alphaInfo == kCGImageAlphaNone) {
        alphaInfo = kCGImageAlphaNoneSkipLast;
    }
    */
    
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    
    /*  switch (orientation) {
     case UIImageOrientationUp:
     {
     //DLog(@"右拍，home键朝右");
     break;
     }
     case UIImageOrientationDown:
     {
     //DLog(@"左拍，home键朝左");
     break;
     }
     case UIImageOrientationLeft:
     {
     //DLog(@"倒拍，home键朝上");
     break;
     }
     case UIImageOrientationRight:
     {
     //DLog(@"竖拍，home键朝下");
     break;
     }
     default:
     break;
     }*/
    
    CGBitmapInfo bitmapInfo =  CGImageGetBitmapInfo(imageRef);

    contextRef = CGBitmapContextCreate(NULL, targetWidth, targetHeight, 8, 0, colorSpaceInfo, bitmapInfo);
    
	if (orientation == UIImageOrientationUp || orientation ==UIImageOrientationDown) {
        CGSize imageSize = sourceImage.size;
        
        CGFloat imageWidth = imageSize.width;
        CGFloat imageHeight = imageSize.height;
        
        CGFloat scaleFactor = 0.0;
        
        CGFloat scaledWidth = targetWidth;
        CGFloat scaledHeight = targetHeight;
        
        CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
        
        if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
            CGFloat widthFactor = targetWidth / imageWidth;
            CGFloat heightFactor = targetHeight / imageHeight;
            
            if (widthFactor > heightFactor) {
                scaleFactor = widthFactor; // scale to fit height
            }
            else {
                scaleFactor = heightFactor; // scale to fit width
            }
            
            scaledWidth  = imageWidth * scaleFactor;
            scaledHeight = imageHeight * scaleFactor;
            
            // center the image
            if (widthFactor > heightFactor)	{
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            }
            else if (widthFactor < heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
        
        // contextRef = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
        //  contextRef = CGBitmapContextCreate(NULL, targetWidth, targetHeight, 8, 0, colorSpaceInfo, bitmapInfo);
        
        //CGColorSpaceRelease(colorSpaceInfo);
        
        CGContextClearRect(contextRef, CGRectMake(0, 0, targetWidth, targetHeight));
        
        if (orientation == UIImageOrientationUp) {//左拍，home键朝左
            
        } else if (orientation == UIImageOrientationDown) {//右拍，home键朝右
            CGContextTranslateCTM (contextRef, targetWidth, targetHeight);
            CGContextRotateCTM (contextRef, -M_PI);
        }
        
        //DLog(@"thumbnailPoint:%@",NSStringFromCGPoint(thumbnailPoint));
        
        CGContextDrawImage(contextRef, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), imageRef);
        
    }
    else if(orientation == UIImageOrientationRight || orientation ==UIImageOrientationLeft){
        
        // contextRef = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
        //contextRef = CGBitmapContextCreate(NULL, targetWidth, targetHeight, 8, 0, colorSpaceInfo, bitmapInfo);
        
        //CGColorSpaceRelease(colorSpaceInfo);
        
        CGContextClearRect(contextRef, CGRectMake(0, 0, targetWidth, targetHeight));
        
        switch (orientation) {
            case UIImageOrientationRight://竖拍 home键在下
            {
                CGContextRotateCTM(contextRef, -M_PI_2);
                CGContextTranslateCTM(contextRef, -targetSize.height,0.0);
                break;
            }
            case UIImageOrientationLeft://倒拍 home键在上
            {
                CGContextRotateCTM(contextRef, -M_PI_2);
                CGContextTranslateCTM(contextRef, -targetHeight,0.0);
                
                CGContextRotateCTM(contextRef, M_PI);
                CGContextTranslateCTM(contextRef, -targetHeight,-targetWidth);
                
                break;
            }
            default:
                break;
        }
        
        CGContextDrawImage(contextRef, CGRectMake(0, 0, targetSize.height, targetSize.width), sourceImage.CGImage);
    }
    
    resultImageRef=CGBitmapContextCreateImage(contextRef);
    CGContextRelease(contextRef);
    
    resultImage= [UIImage imageWithCGImage: resultImageRef];
    CGImageRelease(resultImageRef);
    
    return resultImage;
    
}
-(UIImage *)imageAtRect:(CGRect)rect
{
	
	CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
	UIImage* subImage = [UIImage imageWithCGImage: imageRef];
	CGImageRelease(imageRef);
	
	return subImage;
	
}

- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize {
	
	UIImage *sourceImage = self;
	UIImage *newImage = nil;
	
	CGSize imageSize = sourceImage.size;
	CGFloat width = imageSize.width;
	CGFloat height = imageSize.height;
	
	CGFloat targetWidth = targetSize.width;
	CGFloat targetHeight = targetSize.height;
	
	CGFloat scaleFactor = 0.0;
	CGFloat scaledWidth = targetWidth;
	CGFloat scaledHeight = targetHeight;
	
	CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
	
	if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
		
		CGFloat widthFactor = targetWidth / width;
		CGFloat heightFactor = targetHeight / height;
		
		if (widthFactor > heightFactor) 
			scaleFactor = widthFactor;
		else
			scaleFactor = heightFactor;
		
		scaledWidth  = width * scaleFactor;
		scaledHeight = height * scaleFactor;
		
		// center the image
		
		if (widthFactor > heightFactor) {
			thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
		} else if (widthFactor < heightFactor) {
			thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
		}
	}
	
	
	// this is actually the interesting part:
	
	UIGraphicsBeginImageContext(targetSize);
	
	CGRect thumbnailRect = CGRectZero;
	thumbnailRect.origin = thumbnailPoint;
	thumbnailRect.size.width  = scaledWidth;
	thumbnailRect.size.height = scaledHeight;
	
	[sourceImage drawInRect:thumbnailRect];
	
	newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	if(newImage == nil) NSLog(@"could not scale image");
	
	
	return newImage ;
}


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
	
	UIImage *sourceImage = self;
	UIImage *newImage = nil;
	
	CGSize imageSize = sourceImage.size;
	CGFloat width = imageSize.width;
	CGFloat height = imageSize.height;
	
	CGFloat targetWidth = targetSize.width;
	CGFloat targetHeight = targetSize.height;
	
	CGFloat scaleFactor = 0.0;
	CGFloat scaledWidth = targetWidth;
	CGFloat scaledHeight = targetHeight;
	
	CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
	
	if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
		
		CGFloat widthFactor = targetWidth / width;
		CGFloat heightFactor = targetHeight / height;
		
		if (widthFactor < heightFactor) 
			scaleFactor = widthFactor;
		else
			scaleFactor = heightFactor;
		
		scaledWidth  = width * scaleFactor;
		scaledHeight = height * scaleFactor;
		
		// center the image
		
		if (widthFactor < heightFactor) {
			thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
		} else if (widthFactor > heightFactor) {
			thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
		}
	}
	
	
	// this is actually the interesting part:
	
	UIGraphicsBeginImageContext(targetSize);
	
	CGRect thumbnailRect = CGRectZero;
	thumbnailRect.origin = thumbnailPoint;
	thumbnailRect.size.width  = scaledWidth;
	thumbnailRect.size.height = scaledHeight;
	
	[sourceImage drawInRect:thumbnailRect];
	
	newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	if(newImage == nil) NSLog(@"could not scale image");
	
	
	return newImage ;
}


- (UIImage *)imageByScalingToSize:(CGSize)targetSize {
	
	UIImage *sourceImage = self;
	UIImage *newImage = nil;
	
	//   CGSize imageSize = sourceImage.size;
	//   CGFloat width = imageSize.width;
	//   CGFloat height = imageSize.height;
	
	CGFloat targetWidth = targetSize.width;
	CGFloat targetHeight = targetSize.height;
	
	//   CGFloat scaleFactor = 0.0;
	CGFloat scaledWidth = targetWidth;
	CGFloat scaledHeight = targetHeight;
	CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
	
	// this is actually the interesting part:
	UIGraphicsBeginImageContextWithOptions(targetSize, YES,2.0);
	
	CGRect thumbnailRect = CGRectZero;
	thumbnailRect.origin = thumbnailPoint;
	thumbnailRect.size.width  = scaledWidth;
	thumbnailRect.size.height = scaledHeight;
	
	[sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	if(newImage == nil) NSLog(@"could not scale image");
	
	
	return newImage ;
}


- (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
	return [self imageRotatedByDegrees:CSRadiansToDegrees(radians)];
}

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees 
{   
	// calculate the size of the rotated view's containing box for our drawing space
	UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
	CGAffineTransform t = CGAffineTransformMakeRotation(CSDegreesToRadians(degrees));
	rotatedViewBox.transform = t;
	CGSize rotatedSize = rotatedViewBox.frame.size;
	
	// Create the bitmap context
	UIGraphicsBeginImageContext(rotatedSize);
	CGContextRef bitmap = UIGraphicsGetCurrentContext();
	
	// Move the origin to the middle of the image so we will rotate and scale around the center.
	CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
	
	//   // Rotate the image context
	CGContextRotateCTM(bitmap, CSDegreesToRadians(degrees));
	
	// Now, draw the rotated/scaled image into the context
	CGContextScaleCTM(bitmap, 1.0, -1.0);
	CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
	
	UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
	
}
-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
    UIGraphicsBeginImageContext(image.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
	CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
	CGContextAddEllipseInRect(context, rect);
	CGContextClip(context);
	
	[image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
	CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}
@end;